let fs=require('fs');
let path=require('path');
let router=require('koa-router')();

function searchControlersFiles(){
    let files= fs.readdirSync(__dirname);

    return files.filter(item=>{
        return item.endsWith('.js') && item != 'index.js';
    });
}

function registerControlersFiles(currentPath,files){
    files.forEach(item=>{
        let fullPath=path.join(currentPath,item);
        let routes=require(fullPath);

        for(let key in routes){
            let type=routes[key][0];
            let fn=routes[key][1];

            if(type==='get'){
                router.get(key,fn);
            }else{
                router.post(key,fn);
            }
        }
    })
}


module.exports=function(){
    let defaultDir='/controlers';
    let currentPath=path.resolve('.');
    let fullPath= path.join(currentPath,defaultDir);

    let files=searchControlersFiles();
    registerControlersFiles(fullPath,files);

    return router.routes();
}